import React, { useState, useRef, useEffect } from 'react';
import './App.css';
import MainLayout from './components/layout/MainLayout.tsx';
import FileTree from './components/novelTree/FileTree.tsx';
import TextEditor from './components/editor/TextEditor.tsx';
import AIChatPanel from './components/aiChat/AIChatPanel.tsx';
import SettingsPanel from './components/settings/SettingsPanel.tsx';
import TestImportPage from './components/fileSystem/TestImportPage.tsx';
import Toast from './components/ui/Toast.tsx';
import { IconButton, Drawer, Box, Button } from '@mui/material';
import { Settings as SettingsIcon } from '@mui/icons-material';
import { SelectedTextInfo, PolishType } from './types/text.ts';

/**
 * 应用主组件
 */
function App() {
  // 状态
  const [selectedText, setSelectedText] = useState<string>('');
  const [selectionInfo, setSelectionInfo] = useState<SelectedTextInfo | null>(null);
  const [activePolishType, setActivePolishType] = useState<PolishType | null>(null);
  const [showSettings, setShowSettings] = useState<boolean>(false);
  const [showTestPage, setShowTestPage] = useState<boolean>(false);
  
  // 创建TextEditor的ref
  const textEditorRef = useRef<{ replaceSelectedText: (text: string, options?: any) => boolean }>(null);
  
  // 缓存上次处理的文本，避免重复处理
  const lastProcessedTextRef = useRef<string>('');

  /**
   * 处理编辑器中文本选择事件
   */
  const handleTextSelection = (text: string, info?: SelectedTextInfo) => {
    // 输出完整的调试信息
    console.log("App handleTextSelection 被调用:", {
      文本长度: text ? text.length : 0,
      文本前50字符: text ? text.substring(0, 50) : '',
      info: info,
      时间戳: new Date().toISOString()
    });

    // 验证文本有效性
    if (!text || text.trim().length === 0) {
      console.log("App: 收到的选中文本为空，不处理");
      return;
    }

    // 更新lastProcessedTextRef
    lastProcessedTextRef.current = text;

    // 始终更新选中文本状态
    setSelectedText(text);
    if (info) {
      setSelectionInfo(info);
    } else {
      // 如果没有提供info，创建一个基本的信息对象
      setSelectionInfo({
        text: text,
        sourceId: '未知来源',
        startPosition: 0,
        endPosition: text.length,
        timestamp: Date.now(),
        type: 'text'
      });
    }

    // 重置润色类型
    setActivePolishType(null);

    console.log("App: 已更新选中文本状态", text.substring(0, 50));
  };

  /**
   * 处理润色类型选择
   */
  const handlePolishTypeSelect = (type: PolishType, info: SelectedTextInfo) => {
    // 设置选中文本
    setSelectedText(info.text);
    setSelectionInfo(info);

    // 设置当前活动的润色类型
    setActivePolishType(type);

    console.log('选择润色类型:', type, info);
  };

  /**
   * 处理AI建议应用事件
   */
  const handleApplySuggestion = (suggestion: string) => {
    // TODO: 实现AI建议应用到编辑器的逻辑
    console.log('应用AI建议:', suggestion);
  };

  /**
   * 切换设置面板显示状态
   */
  const toggleSettings = () => {
    setShowSettings(!showSettings);
  };

  /**
   * 切换测试页面显示状态
   */
  const toggleTestPage = () => {
    setShowTestPage(!showTestPage);
  };

  // 设置按钮组件
  const settingsButton = (
    <IconButton
      color="inherit"
      onClick={toggleSettings}
      aria-label="设置"
      size="large"
    >
      <SettingsIcon />
    </IconButton>
  );

  // 渲染主内容
  const renderMainContent = () => {
    if (showTestPage) {
      return <TestImportPage />;
    }

    return (
      <TextEditor
        ref={textEditorRef}
        onTextSelection={handleTextSelection}
        onPolishTypeSelect={handlePolishTypeSelect}
      />
    );
  };

  // 添加测试按钮
  const additionalActions = (
    <Box sx={{ display: 'flex', alignItems: 'center' }}>
      <Button
        color="inherit"
        onClick={toggleTestPage}
        size="small"
        variant={showTestPage ? "contained" : "text"}
        sx={{ mr: 1 }}
      >
        {showTestPage ? "返回编辑器" : "文件导入测试"}
      </Button>
      {settingsButton}
    </Box>
  );

  return (
    <Box sx={{ position: 'relative', height: '100vh' }}>
      {/* 主布局 */}
      <MainLayout
        leftPanel={<FileTree />}
        mainContent={renderMainContent()}
        rightPanel={
          <AIChatPanel
            selectedText={selectedText}
            selectionInfo={selectionInfo}
            onApplyAISuggestion={handleApplySuggestion}
          />
        }
        actions={additionalActions}
      />

      {/* 设置面板抽屉 */}
      <Drawer
        anchor="right"
        open={showSettings}
        onClose={toggleSettings}
        sx={{
          '& .MuiDrawer-paper': {
            width: { xs: '100%', sm: '450px' },
            maxWidth: '100%'
          },
        }}
      >
        <SettingsPanel />
      </Drawer>
      
      {/* 全局Toast提示 */}
      <Toast />
    </Box>
  );
}

export default App;
